import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score, mean_absolute_error, mean_squared_error
from PIL import Image
import pickle


img_path = "0.jpg"#原/home/pi/Code/0.jpg
model_path = 'model' #原/home/pi/Code/model 真实的模型

def rgb2hsv(r, g, b):
    r, g, b = r/255.0, g/255.0, b/255.0
    mx = max(r, g, b)
    mn = min(r, g, b)
    m = mx-mn
    if mx == mn:
        h = 0
    elif mx == r:
        if g >= b:
            h = ((g-b)/m)*60
        else:
            h = ((g-b)/m)*60 + 360
    elif mx == g:
        h = ((b-r)/m)*60 + 120
    elif mx == b:
        h = ((r-g)/m)*60 + 240
    if mx == 0:
        s = 0
    else:
        s = m/mx
    v = mx
    return h, s, v


def rgb2lab(r, g, b):
    r = r/ 255.0  # rgb range: 0 ~ 1
    g = g / 255.0
    b = b / 255.0
 
    # gamma 2.2
    if r > 0.04045:
        r = pow((r + 0.055) / 1.055, 2.4)
    else:
        r = r / 12.92
 
    if g > 0.04045:
        g = pow((g + 0.055) / 1.055, 2.4)
    else:
        g = g / 12.92
 
    if b > 0.04045:
        b = pow((b + 0.055) / 1.055, 2.4)
    else:
        b = b / 12.92
 
    # sRGB
    X = r * 0.436052025 + g * 0.385081593 + b * 0.143087414
    Y = r * 0.222491598 + g * 0.716886060 + b * 0.060621486
    Z = r * 0.013929122 + g * 0.097097002 + b * 0.714185470
 
    # XYZ range: 0~100
    X = X * 100.000
    Y = Y * 100.000
    Z = Z * 100.000
 
    # Reference White Point
 
    ref_X = 96.4221
    ref_Y = 100.000
    ref_Z = 82.5211
 
    X = X / ref_X
    Y = Y / ref_Y
    Z = Z / ref_Z
 
    # Lab
    if X > 0.008856:
        X = pow(X, 1 / 3.000)
    else:
        X = (7.787 * X) + (16 / 116.000)
 
    if Y > 0.008856:
        Y = pow(Y, 1 / 3.000)
    else:
        Y = (7.787 * Y) + (16 / 116.000)
 
    if Z > 0.008856:
        Z = pow(Z, 1 / 3.000)
    else:
        Z = (7.787 * Z) + (16 / 116.000)
 
    Lab_L = round((116.000 * Y) - 16.000, 2)
    Lab_a = round(500.000 * (X - Y), 2)
    Lab_b = round(200.000 * (Y - Z), 2)
 
    return Lab_L, Lab_a, Lab_b

class img_process:
    def __init__(self) :
        self.RIO_num = 10
        self.name = ".bmp"

    def improcess_etory(self, img):
        pi=[]   
        std=[]   
        std3=[]    
        con = []  
        ent = []
        result = []
        hist,bins = np.histogram(img.flatten(),256,[0,256])#计算灰度直方图
        cdf = hist.cumsum()
        cdf_normalized = hist / cdf.max()#归一化
        #计算均值
        for i in range(256):
            p = cdf_normalized[i]*i
            pi.append(p)
        mean = sum((pi))
        result.append(mean)
        #计算方差（二阶矩）
        for i in range(256):
            s = (i-mean)**2*cdf_normalized[i]
            std.append(s)
        standard = sum(std)
        result.append(standard)
        #计算三阶矩
        for i in range(256):
            s3 = (i-mean)**3*cdf_normalized[i]
            std3.append(s3)
        standard3 = sum(std3)
        result.append(standard3)
        #计算一致性
        for i in range(256):
            c = cdf_normalized[i]**2
            con.append(c)
        consistency = sum(con)
        result.append(consistency)
        #计算熵
        for i in range(256):
            e = -(cdf_normalized[i]*np.log2(cdf_normalized[i]+0.00001))
            ent.append(e)
        entropy = sum(ent)
        result.append(entropy)
        return result

    def improcess_color(self, img):
        color = []
#        b, g, r = cv2.split(img)
        r = img[:, :, 0]
        g = img[:, :, 1]
        b = img[:, :, 2]
        B_img = np.sum(b)/np.size(b)
        color.append(B_img)
        G_img = np.sum(g)/np.size(g)
        color.append(G_img)
        R_img = np.sum(r)/np.size(r)
        color.append(R_img)

        h, s, v = rgb2hsv(R_img, G_img, B_img)
        H_img = np.sum(h)/np.size(h)
        color.append(H_img)
        S_img = np.sum(s)/np.size(s)
        color.append(S_img)
        V_img = np.sum(v)/np.size(v)
        color.append(V_img)

        L, a, b = rgb2lab(R_img, G_img, B_img)
        L_img = np.sum(L)/np.size(L)
        color.append(L_img)
        a_img = np.sum(a)/np.size(a)
        color.append(a_img)
        b_img = np.sum(b)/np.size(b)
        color.append(b_img)


        return color

    def read_img(self,path="/media/xiebm/Xie/xie/New20211124/0_0_.bmp"):
        image = np.array(Image.open(path))
#        y, x = image.shape[0:2]
#        ptRectLeftUp = (int(x/self.RIO_num), int(y/self.RIO_num))     # (h, w) -> (x, y)
#        ptRectRightDown = (int(x-x/self.RIO_num), int(y-y/self.RIO_num))
#        result = image[int(y/self.RIO_num):int(y-y/self.RIO_num), int(x/self.RIO_num):int(x-x/self.RIO_num)]
#        result_show = cv2.resize(result, (int(x/4), int(y/4)))
        return image

    def read_path(self, filepath="/media/xiebm/Xie/xie/New20211125/", log = False):
        img = Image.open(filepath)
        img = img.resize((640,480),Image.ANTIALIAS)
        img_temp = np.array(img)
        Data = []
        if  img_temp is None:
            print(filepath, "是空")
        else:
            img = self.read_img(filepath)
            etory = self.improcess_etory(img)
            color = self.improcess_color(img)
            if log:
                f = open("002.csv", "a")
            for e in etory:
                Data.append(e)
                if log:
                    f.write(str(e))
                    f.write(',')
            for c in color:
                Data.append(c)
                if log:
                    f.write(str(c))
                    f.write(',')
            if log:
                f.close()
            Data = np.array(Data)
            return Data.reshape(1, -1)

def img_predict():#预测图片
    img = img_process()
    Data = img.read_path(filepath = img_path)
    loaded_model = pickle.load(open(model_path, 'rb'))
    y = loaded_model.predict(Data)
    y = y.reshape(1,-1)

    return y[0][0]

def get_water():
    y = img_predict()#0.666
    return y

print(get_water())